package com.lemon.smartsafety.ui.fragment.safe.data;

import android.Manifest;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.widget.LinearLayoutManager;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.ldzs.recyclerlibrary.Mode;
import com.ldzs.recyclerlibrary.PullToRefreshRecyclerView;
import com.lemon.android.http.LemonRequestParams;
import com.lemon.smartsafety.R;
import com.lemon.smartsafety.app.AppService;
import com.lemon.smartsafety.app.BundleKey;
import com.lemon.smartsafety.app.Constants;
import com.lemon.smartsafety.app.EventTag;
import com.lemon.smartsafety.app.IApplication;
import com.lemon.smartsafety.app.RefreshType;
import com.lemon.smartsafety.entity.event.datacoll.BuildingCheckItemDeleteEvent;
import com.lemon.smartsafety.entity.event.datacoll.BuildingCheckItemEditEvent;
import com.lemon.smartsafety.entity.event.datacoll.BuildingCheckItemRefreshEvent;
import com.lemon.smartsafety.entity.event.datacoll.BuildingCheckItemViewFlowEvent;
import com.lemon.smartsafety.entity.event.datacoll.BuildingPositionRefreshEvent;
import com.lemon.smartsafety.entity.event.http.HttpCallbackEvent;
import com.lemon.smartsafety.entity.safe.company.BindNfcEvent;
import com.lemon.smartsafety.entity.safe.company.BindQrcodeEvent;
import com.lemon.smartsafety.entity.safe.company.BuildingCheckItemViewNfcEvent;
import com.lemon.smartsafety.entity.safe.company.BuildingCheckItemViewQrcodeEvent;
import com.lemon.smartsafety.entity.safe.company.CompanyBuildingCheckItemExistVo;
import com.lemon.smartsafety.entity.safe.company.CompanyBuildingCheckItemVo;
import com.lemon.smartsafety.entity.safe.company.CompanyBuildingIndexVo;
import com.lemon.smartsafety.entity.safe.company.CompanyBuildingItemCountVo;
import com.lemon.smartsafety.entity.safe.company.CompanyBuildingVo;
import com.lemon.smartsafety.http.callback.HandlerCallback;
import com.lemon.smartsafety.http.service.SafeDataServices;
import com.lemon.smartsafety.listener.PullRefreshListener;
import com.lemon.smartsafety.tag.BaseTAG;
import com.lemon.smartsafety.tag.DefaultCode;
import com.lemon.smartsafety.ui.activity.safe.data.BuildingCheckItemBindNfcActivity;
import com.lemon.smartsafety.ui.activity.safe.data.BuildingCheckItemFlowListActivity;
import com.lemon.smartsafety.ui.activity.safe.data.BuildingCheckItemPropActivity;
import com.lemon.smartsafety.ui.adapter.safe.data.BuildingCheckItemAdapter;
import com.lemon.smartsafetynew.ui.fragment.base.BaseFragment;
import com.lemon.smartsafety.utils.CommonUtil;
import com.lemon.smartsafety.utils.LogUtils;
import com.lemon.smartsafety.utils.app.HUDUtil;
import com.lemon.smartsafety.utils.app.ToastUtil;
import com.lemon.smartsafety.utils.app.UIHelper;
import com.lemon.smartsafety.utils.common.LoggerHelper;
import com.lemon.smartsafety.utils.common.StringUtils;
import com.lemon.smartsafety.view.list.MultiStateView;
import com.lemon.smartsafetynew.entity.event.patrol.OneKeyBindEvent;
import com.lemon.smartsafetynew.ui.activity.qrcode.QRcodeActivity;
import com.lemon.smartsafetynew.util.constants.KeyConstants;

import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import cn.finalteam.galleryfinal.permission.EasyPermissions;
import kale.adapter.LemonRcvAdapter;

/**
 * 检查项目 现有检查项目列表
 */
public class BuildingCheckItemListFragment extends BaseFragment implements PullRefreshListener {
    private LoggerHelper loggerHelper = new LoggerHelper(BuildingCheckItemListFragment.class);


    @Bind(R.id.pullToRefreshRecyclerView)
    public PullToRefreshRecyclerView mPullToRefreshRecyclerView;

    @Bind(R.id.multiStateView)
    public MultiStateView mMultiStateView;


    protected int currentPage = Constants.DEFAULT_FIRST_PAGE_NUMBER;

    protected int pageSize = Constants.PAGE_SIZE;

    public List<CompanyBuildingCheckItemVo> mDataList = new ArrayList<>();

    protected LemonRcvAdapter<CompanyBuildingCheckItemVo> mAdapter;


    /**
     * bundle info
     */
    private CompanyBuildingVo          mCompanyBuildingVo;
    private CompanyBuildingIndexVo     mCompanyBuildingIndexVo;
    private CompanyBuildingItemCountVo mCompanyBuildingItemCountVo;



    private CompanyBuildingCheckItemVo bindData=null;

    public static BuildingCheckItemListFragment newInstance() {
        return new BuildingCheckItemListFragment();
    }


    private String mKeyWord = "";


    //add by Andrew.yin 2017/9/13 begin
    private String qr_code = "";
    private String nfc_code = "";
    //add by Andrew.yin 2017/9/13 end

    protected void getBaseArguments() {
        if (getArguments() != null) {
            mKeyWord = StringUtils.nullValue(getArguments().getString(BundleKey.KEY_WORD));
            mCompanyBuildingVo = (CompanyBuildingVo) getArguments().getSerializable(BundleKey.COMPANY_BUILD_INFO);
            mCompanyBuildingIndexVo = (CompanyBuildingIndexVo) getArguments().getSerializable(BundleKey.COMPANY_BUILDING_INDEX_VO);
            mCompanyBuildingItemCountVo = (CompanyBuildingItemCountVo) getArguments().getSerializable(BundleKey.COMPANY_BUILDING_ITEM_COUNT);
        }

    }

    @Override
    protected int getContentViewId() {
        return R.layout.fragment_refresh_no_title;
    }

    @Override
    protected void initViews() {
        pageSize = Integer.MAX_VALUE;//这样设置一下，就不就有加载更多了
        LinearLayoutManager layoutManager = new LinearLayoutManager(IApplication.context(), LinearLayoutManager.VERTICAL, false);
        mPullToRefreshRecyclerView.setRefreshMode(Mode.PULL_FROM_START);
        mPullToRefreshRecyclerView.setLayoutManager(layoutManager);
        mAdapter = getLemonAdapter();
        mPullToRefreshRecyclerView.setAdapter(mAdapter);
        mPullToRefreshRecyclerView.setOnPullUpToRefreshListener(new PullToRefreshRecyclerView.OnPullUpToRefreshListener() {
            @Override
            public void onRefresh() {
                currentPage = Constants.DEFAULT_FIRST_PAGE_NUMBER;
                onPullRefresh();
            }
        });

        mPullToRefreshRecyclerView.setRefreshMode(Mode.PULL_FROM_START);

        mPullToRefreshRecyclerView.beginRefreshing();

        initGalleryFinalImageLoader();
    }

    public LemonRcvAdapter<CompanyBuildingCheckItemVo> getLemonAdapter() {
        return new BuildingCheckItemAdapter(mDataList);
    }


    @Override
    public void onPullRefresh() {
        //changed by Andrew.yin 2017/9/19 begin 修改获取检查项列表接口
        //SafeDataServices.init().getCheckItemList(mCompanyBuildingItemCountVo.getBuildingId(), mCompanyBuildingItemCountVo.getFloorNumber(), mCompanyBuildingItemCountVo.getPositionMark(), mKeyWord);

        LemonRequestParams params = new LemonRequestParams("");
        params.put("building_id", mCompanyBuildingItemCountVo.getBuildingId());
        params.put("floor_num", mCompanyBuildingItemCountVo.getFloorNumber());
        params.put("position_mark", mCompanyBuildingItemCountVo.getPositionMark());
        SafeDataServices.init().getCheckItems(params);
        //changed by Andrew.yin 2017/9/19 end
    }


    /**
     * 数据请求事件
     *
     * @param event
     */
    @Subscribe
    public void onEventMainThread(HttpCallbackEvent<CompanyBuildingCheckItemExistVo> event) {
        //if (EventTag.TAG_SAFE_DATA_COLLECTION_BUILDING_CHECK_ITEM_LIST.equals(event.getTag())) {
        if (KeyConstants.URL_GET_BUILDING_FLOOR_POSITION_CHECK_ITEM_LIST.equals(event.getTag())) {  //刷新列表
            if (HandlerCallback.HttpFlow.START == event.getHttpFlow()) {
            } else if (HandlerCallback.HttpFlow.FINISH == event.getHttpFlow()) {
                RefreshType type = (RefreshType) event.getOther();
                if (RefreshType.REFRESH == type) {
                    mPullToRefreshRecyclerView.onRefreshComplete();
                }
                if (Constants.Result.SUCCESS == event.getEventResult()) {
                    if (RefreshType.REFRESH == type) {
                        httpRefresh(event.getObj().getItemlist());
                    }
                    currentPage++;
                } else if (Constants.Result.ERROR == event.getEventResult()) {
                    if (RefreshType.REFRESH == type) {
                        httpRefreshError(event.getMsg());
                    }
                }
            }
        } else if (EventTag.TAG_SAFE_DATA_COLLECTION_BUILDING_CHECK_ITEM_DELETE_ACTION.equals(event.getTag())) { //删除检查项
            if (HandlerCallback.HttpFlow.START == event.getHttpFlow()) {
                mHUDUtil.showHUD();
            } else if (HandlerCallback.HttpFlow.FINISH == event.getHttpFlow()) {
                if (Constants.Result.SUCCESS == event.getEventResult()) {
                    LogUtils.LOGE("删除成功");

                    AppService.getBus().post( new BuildingPositionRefreshEvent(BuildingPositionRefreshEvent.class.getName()));
                    mHUDUtil.showDoneTip(event.getMsg(), new HUDUtil.CallBack() {
                        @Override
                        public void onCall() {
                            mPullToRefreshRecyclerView.beginRefreshing();
                        }
                    });
                } else if (Constants.Result.ERROR == event.getEventResult()) {
                    mHUDUtil.showErrorTip(event.getMsg());
                }
            }
        }
    }


    public void httpRefresh(List<CompanyBuildingCheckItemVo> data) {
        if (data != null && !data.isEmpty()) {
            mMultiStateView.setViewState(MultiStateView.VIEW_STATE_CONTENT);
            if (data.size() < pageSize) {
                mPullToRefreshRecyclerView.setRefreshMode(Mode.PULL_FROM_START);
            } else {
                mPullToRefreshRecyclerView.setRefreshMode(Mode.PULL_FROM_START);
            }
            mDataList.clear();
            mAdapter.notifyDataSetChanged();
            mAdapter.addItems(data);
        } else {
            mMultiStateView.setViewState(MultiStateView.VIEW_STATE_EMPTY);
        }
    }


    public void httpRefreshError(String msg) {
        mHUDUtil.showErrorTip(msg);
        mMultiStateView.setErrorTip(msg);
        mMultiStateView.setViewState(MultiStateView.VIEW_STATE_ERROR);
        mMultiStateView.setErrorTip(msg);
    }


    //OnEventHandler

    /**
     * 删除事件
     *
     * @param event
     */
    @Subscribe
    public void onEventMainThread(final BuildingCheckItemDeleteEvent event) {
        LogUtils.LOGE("删除事件");
        new MaterialDialog.Builder(getContext()).title(R.string.tip_str_title).content(R.string.is_delete).positiveText(R.string.sure_str).negativeText(R.string.cancel_str).onAny(new MaterialDialog.SingleButtonCallback() {
            @Override
            public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                if (which == DialogAction.POSITIVE) {
                    SafeDataServices.init().deleteCheckItem(event.getData().getItemId());
                }
            }
        }).show();
    }


    /**
     * 编辑事件
     *
     * @param event
     */
    @Subscribe
    public void onEventMainThread(BuildingCheckItemEditEvent event) {
        LogUtils.LOGE("编辑事件");
        Bundle bundle = new Bundle();
        bundle.putSerializable(BundleKey.COMPANY_BUILD_INFO, mCompanyBuildingVo);
        bundle.putSerializable(BundleKey.COMPANY_BUILDING_ITEM_COUNT, mCompanyBuildingItemCountVo);
        bundle.putSerializable(BundleKey.COMPANY_BUILDING_INDEX_VO, mCompanyBuildingIndexVo);
        bundle.putSerializable(BundleKey.COMPANY_BUILDING_CHECK_ITEM_VO, event.getData());//编辑的Vo
        UIHelper.showActivity(getContext(), bundle, BuildingCheckItemPropActivity.class);
    }


//    /**
//     * 查看照片
//     *
//     * @param event
//     */
//    @Subscribe
//    public void onEventMainThread(HorizontalEvidenceEvent event) {
//        mHUDUtil.showDoneTip("见到这个消息请联系管理员");
//        List<EvidenceDataI> res = event.getData();
//        if (res != null && res.size() != 0) {
//            EvidenceDataI data = res.get(event.getPosition());
//            if (LemonFileHelper.isImageUrl(data.getEvidenceUrl())) {
//                List<PhotoInfo> photos = HorizontalEvidenceAdapter.getPhotoInfoList(event.getData());
//                if (photos != null && photos.size() != 0) {
//                    UIHelper.showPhotoView(this, photos, event.getPosition());
//                }
//            } else if (LemonFileHelper.isVoiceUrl(data.getEvidenceUrl())) {
//                playVoice(HttpUtils.formatFilesUrl(data.getEvidenceUrl()));
//            }
//        }
//    }


    /**
     * 刷新事件
     *
     * @param event
     */
    @Subscribe
    public void onEventMainThread(BuildingCheckItemRefreshEvent event) {
        if (BuildingCheckItemRefreshEvent.class.getName().equals(event.getTag())) {
            mPullToRefreshRecyclerView.beginRefreshing();
        }
    }


    /**
     * 查看检查流程
     *
     * @param event
     */
    @Subscribe
    public void onEventMainThread(final BuildingCheckItemViewFlowEvent event) {
        if (BuildingCheckItemViewFlowEvent.class.getName().equals(event.getTag())) {
            Bundle bundle = new Bundle();
            bundle.putSerializable(BundleKey.COMPANY_BUILDING_CHECK_ITEM_VO, event.getData());
            UIHelper.showActivity(getContext(), bundle, BuildingCheckItemFlowListActivity.class);
        }
    }

    /**
     * 适配器绑定NFC
     *
     * @param event
     */
    @Subscribe
    public void onEventMainThread(final BuildingCheckItemViewNfcEvent event) {
        if (BuildingCheckItemViewNfcEvent.class.getName().equals(event.getTag())) {

            bindData=event.getData();

            //UIHelper.showActivity(getContext(),BuildingCheckItemBindNfcActivity.class);
            //if(bindData.getBindingNfcStatus().equals("1")){
            if(!bindData.getBindingNfcStatus().equals("0")){
                getConfirmDialog("该检查项目已绑定NFC是否需要重新绑定", new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                        if (which == DialogAction.POSITIVE) {
                            startNfc();
                        }
                    }
                }).show();
            }else{
                startNfc();
            }

        }
    }

    private void startNfc(){
        Bundle bundle = new Bundle();
        bundle.putString(BaseTAG.COMMON_BASE_TAG, BuildingCheckItemListFragment.class.getName());
        UIHelper.showActivity(getContext(), bundle, BuildingCheckItemBindNfcActivity.class);
    }


    /**
     * 适配器绑定二维码
     *
     * @param event
     */
    @Subscribe
    public void onEventMainThread(final BuildingCheckItemViewQrcodeEvent event) {
        if (BuildingCheckItemViewQrcodeEvent.class.getName().equals(event.getTag())) {

            bindData=event.getData();
            //if(bindData.getBindingQrcodeStatus().equals("1")){
            if(!bindData.getBindingQrcodeStatus().equals("0")){
                getConfirmDialog("该检查项目已绑定二维码是否需要重新绑定", new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                        if (which == DialogAction.POSITIVE) {
                            if(getOpenCameraEasyPermissions()){
                                startQrcode();
                            }
                        }
                    }
                }).show();
            }else{
                if(getOpenCameraEasyPermissions()){
                    startQrcode();
                }
            }

        }
    }

    /**
     * @return  不知为何 华为手机申请摄像头权限会崩溃
     */
    private boolean getOpenCameraEasyPermissions(){

        if (EasyPermissions.hasPermissions(getActivity(), Manifest.permission.CAMERA)) {
            // Have permission, do the thing!
            return true;
        } else {
            // Ask for one permission
/*            EasyPermissions.requestPermissions(this, "需要请求camera权限",
                    REQUEST_CAMERA_PERM, Manifest.permission.CAMERA);*/
            ToastUtil.show("请允许摄像头权限");
            return false;
        }

      /*  if (Build.VERSION.SDK_INT >= 23) {
            int checkCallPhonePermission = ContextCompat.checkSelfPermission(getContext(), Manifest.permission.CAMERA);
            if (checkCallPhonePermission != PackageManager.PERMISSION_GRANTED) {
                try {
                    requestPermissions( new String[]{Manifest.permission.CAMERA}, RulesUtils.REQUEST_CODE_ASK_CAMERA);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return false;
            } else {
                return true;
            }
        } else {
            return true;
        }*/
    }





    private void startQrcode(){
        try {
            //Intent intent = new Intent(getActivity(), CaptureActivity.class);
            Intent intent = new Intent(getActivity(), QRcodeActivity.class);
            getActivity().startActivityForResult(intent, DefaultCode.REQUEST_CODE);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 适配器 一键绑定
     */
    @Subscribe
    public void onOneKeyEvent(final OneKeyBindEvent event) {
        if (OneKeyBindEvent.class.getName().equals(event.getTag())) {

            bindData=event.getData();
            //if(bindData.getBindingQrcodeStatus().equals("1")){
            if(!bindData.getBindingQrcodeStatus().equals("0")){
                getConfirmDialog("该检查项目已绑定二维码是否需要重新绑定", new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                        if (which == DialogAction.POSITIVE) {
                            if(getOpenCameraEasyPermissions()){
                                startQrcodeOneKey();
                            }
                        }
                    }
                }).show();
            }else{
                if(getOpenCameraEasyPermissions()){
                    startQrcodeOneKey();
                }
            }

        }
    }

    /**
     * 一键绑定 扫描二维码
     */
    private void startQrcodeOneKey() {
        //Intent intent = new Intent(getActivity(), CaptureActivity.class);
        Intent intent = new Intent(getActivity(), QRcodeActivity.class);
        intent.setAction(OneKeyBindEvent.class.getName());
        getmContext().startActivityForResult(intent, DefaultCode.REQUEST_CODE);
    }

    /**
     * 一键绑定 扫描NFC
     */
    private void startNfcOneKey(){
        Bundle bundle = new Bundle();
        bundle.putString(BaseTAG.COMMON_BASE_TAG, OneKeyBindEvent.class.getName());
        UIHelper.showActivity(getContext(), bundle, BuildingCheckItemBindNfcActivity.class);
    }

    /**
     * 绑定NFC的返回通知
     *
     * @param event
     */
    @Subscribe
    public void onEventMainThread(final BindNfcEvent event) {
        if(BuildingCheckItemListFragment.class.getName().equals(event.getTag())) {
            if (!CommonUtil.strIsEmpty(event.getCode())) {
                LogUtils.LOGE("绑定NFC:" + event.getCode());
                if (CommonUtil.objIsEmpty(bindData)) {
                    return;
                }
                //bindCodeHttp(1,event.getCode(), bindData.getItemId());
                bindCodeHttp(1, "", event.getCode(), bindData.getItemId());
            }
        } else if (OneKeyBindEvent.class.getName().equals(event.getTag())) { //一键绑定
            if (!CommonUtil.strIsEmpty(event.getCode())) {
                LogUtils.LOGE("绑定NFC:" + event.getCode());
                if (CommonUtil.objIsEmpty(bindData)) {
                    return;
                }
                nfc_code = event.getCode();
                //Log.e("yxy", "qrcode = " + qr_code + " nfc_code" + nfc_code);
                bindCodeHttp(2, qr_code, nfc_code, bindData.getItemId());
            }
        }
    }


    /**
     * 绑定二维码的返回通知
     *
     * @param event
     */
    @Subscribe
    public void onEventMainThread(final BindQrcodeEvent event) {
        if(BuildingCheckItemListFragment.class.getName().equals(event.getTag())) {
            if (!CommonUtil.strIsEmpty(event.getCode())) {

                LogUtils.LOGE("绑定二维码:" + event.getCode());

                if (CommonUtil.objIsEmpty(bindData)) {
                    return;
                }
                //bindCodeHttp(0, event.getCode(), bindData.getItemId());
                bindCodeHttp(0, event.getCode(), "", bindData.getItemId());
            }
        } else if (OneKeyBindEvent.class.getName().equals(event.getTag())) { //一键绑定

            if (!CommonUtil.strIsEmpty(event.getCode())) {

                LogUtils.LOGE("获取二维码:" + event.getCode());
                qr_code = event.getCode();

                startNfcOneKey();
            }
        }
    }






/*   //**
     * 绑定NFC 或者二维码
     * @param type       0为 二维码    1为NFC
     * @param code
     * @param item_id
     *//*
    public void bindCodeHttp(int type,String  code, String item_id) {
        LemonRequestParams params = new LemonRequestParams("user_company_relation", "relation_id", "");
        if(type==1) {
            params.put("handler", "com.lemon.mobile.qrcode.BindingNFCAction");
            params.put("op", "binding_nfc");

            params.put("qrcode_code", code, Field.TYPE_STRING);
            params.put("item_id", item_id, Field.TYPE_STRING);
            params.put("company_code", mCompanyBuildingVo.getCompanyCode(), Field.TYPE_STRING);

            params.put("_no_html", "1");
        }else{
            params.put("handler", "com.lemon.mobile.qrcode.BindingQrcodeAction");
            params.put("op", "binding_qrcode");

            params.put("qrcode_code", code, Field.TYPE_STRING);
            params.put("item_id", item_id, Field.TYPE_STRING);
            //params.put("company_code", mCompanyBuildingVo.getCompanyCode(), Field.TYPE_STRING);

            params.put("_no_html", "1");
        }

        SharedPreferencesServer mSharedPreferencesServer = new SharedPreferencesServer(getContext());
        String serverUrl = mSharedPreferencesServer.getRequestUrl(UrlInfo.BindNfc);
        mHUDUtil.show();
        HttpOkBase.httpBasePost(params, serverUrl, "", new HttpOkBase.HttpInterface() {
            @Override
            public void callBackFunction(boolean httpClient, String result) {

                mHUDUtil.hidden();
                if (httpClient) {
                    BaseMode baseMode = JsonUtils.fromJson(result, BaseMode.class);
                    if (!CommonUtil.objIsEmpty(baseMode)) {
                        if (HttpBack.httpBackError(baseMode)) {
                            ToastUtils.toastMsg(baseMode.getMsg());
                            //刷新当前页面
                            currentPage = Constants.DEFAULT_FIRST_PAGE_NUMBER;
                            onPullRefresh();
                        } else {
                            mHUDUtil.showErrorTip(baseMode.getMsg());
                        }
                    }
                }
            }
        });

    }
    */

    //add by Andrew.yin 2017/9/19 begin

    /**
     * 绑定标签, NFC QRcode
     * @param type
     * @param qr_code
     * @param nfc_code
     * @param item_id
     */
    public void bindCodeHttp(int type, String qr_code, String nfc_code, String item_id) {

        LemonRequestParams params = new LemonRequestParams("");
        params.put("item_id", item_id);
        if(type == 0) { //绑定二维码
            params.put("qr_code", qr_code);
        } else if (type == 1) { //绑定NFC
            params.put("nfc_code", nfc_code);
        } else if (type == 2) { //一键绑定
            params.put("qr_code", qr_code);
            params.put("nfc_code", nfc_code);
        }

        SafeDataServices
                .init()
                .bindLabel(params);

    }

    @Subscribe
    public void onNetEventMainThread(HttpCallbackEvent<String> event) {
        if (KeyConstants.URL_BIND_LABEL.equals(event.getTag())) {
            if (HandlerCallback.HttpFlow.START == event.getHttpFlow()) {
                mHUDUtil.show();
            } else if (HandlerCallback.HttpFlow.FINISH == event.getHttpFlow()) {
                mHUDUtil.hidden();

                if (Constants.Result.SUCCESS == event.getEventResult()) {

                    String result = event.getObj();
                    processResult(result);

                    currentPage = Constants.DEFAULT_FIRST_PAGE_NUMBER;
                    onPullRefresh();

                }

            }
        }
    }

    private void processResult(String result) {

        boolean isError = false;
        String msg = "";
        if("0".equals(result)) {
            msg = "参数错误";
        } else if("1".equals(result)) {
            msg = "绑定成功";
            isError = true;
        } else if("2".equals(result)) {
            msg = "二维码不存在";
        } else if("3".equals(result)) {
            msg = "二维码已被使用";
        } else if("4".equals(result)) {
            msg = "检查项绑定了多个标签";
        } else if("5".equals(result)) {
            msg = "重新绑定成功";
            isError = true;
        } else if("6".equals(result)) {
            msg = "检查项还未绑定任何标签，绑定NFC失败";
        } else if("7".equals(result)) {
            msg = "标签绑定NFC成功";
            isError = true;
        }

        if(isError) {
            mHUDUtil.showDoneTip(msg, new HUDUtil.CallBack() {
                @Override
                public void onCall() {

                }
            });

        } else {
            mHUDUtil.showErrorTip(msg, new HUDUtil.CallBack() {
                @Override
                public void onCall() {

                }
            });
        }

    }
    //add by Andrew.yin 2017/9/19 end


/*
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        try {
            doNext(requestCode,grantResults);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }



    private void doNext(int requestCode, int[] grantResults) {
        if (requestCode == RulesUtils.REQUEST_CODE_ASK_CAMERA) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // Permission Granted
                LogUtils.LOGE("相机权限申请成功");
                startQrcode();
            } else {
                LogUtils.LOGE("相机权限申请失败");
                // Permission Denied
                ToastUtils.toastMsg("相机权限申请失败,请允许此权限");
            }
        }
    }
*/




}
